<?php

namespace App\Trip\Epidemic\Juhe;

// 查询核酸检测机构
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Cache;

class NucleicAcid extends JuheAbstract
{
    private string $url = 'http://apis.juhe.cn/springTravel/hsjg';

    /**
     * @throws GuzzleException
     * @throws Exception
     */
    public function query($param): static
    {
        $city_id   = $param['city_id'];
        $url       = sprintf($this->url."?key=%s&city_id=%d", $this->key, $city_id);
        $cache_key = "Epidemic:acid:".md5($url);
        if (!Cache::has($cache_key)) {
            $response = $this->client->get($url);
            $contents = $response->getBody()->getContents();
            $res      = json_decode($contents, true);
            if (!isset($res['error_code']) || $res['error_code'] != 0) {
                throw new Exception("error");
            }
            $this->result = $res['result']['data'] ?? [];
            Cache::put($cache_key, $this->result, 30 * config('trip.ttl.day'));
        } else {
            $this->result = Cache::get($cache_key);
        }
        return $this;
    }

    public function getResult(): array
    {
        return $this->result;
    }


}